package com.atguigu.gulimail.product.app;

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryService;
import com.atguigu.common.utils.R;



/**
 * 商品三级分类
 *
 * @author xujiale
 * @email 2519970360@qq.com
 * @date 2023-10-24 15:34:13
 */
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 列表
     */
    @RequestMapping("/list/tree")
    public R list(){
        List<CategoryEntity> listTree=categoryService.listWithTree();//以树形结构返回数据

        return R.ok().put("data",listTree);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{catId}")
    public R info(@PathVariable("catId") Long catId){
		CategoryEntity category = categoryService.getById(catId);

        return R.ok().put("category", category);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody CategoryEntity category){
		categoryService.save(category);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody CategoryEntity category){
		categoryService.updateByIdAndUpdateOther(category);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] catIds){

        //TODO 删除分类前需要判断是否有其他服务引用此分类
		categoryService.removeByIds(Arrays.asList(catIds));

        return R.ok();
    }

    @GetMapping("select/{name}")
    public R selectByName(@PathVariable String name){
        LambdaQueryWrapper<CategoryEntity> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(!name.isEmpty(),CategoryEntity::getName,name);
        List<CategoryEntity> entity = categoryService.list(lambdaQueryWrapper);
        return R.ok().put("entity", entity);
    }

}
